from decimal import Decimal
from flask import Flask, request, render_template, redirect, session, jsonify, send_file
from werkzeug.security import generate_password_hash, check_password_hash
import os
from connect_sql import con_sql
import pymysql
import datetime
import random
import string
import subprocess
import pandas as pd
import io
from io import BytesIO


app = Flask(__name__)
app.secret_key = 'secret_key' 

template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../前端/templates')
app.template_folder = template_dir
# print(f"模板文件夹路径：{template_dir}")  # 打印路径，确认是否正确

def get_user_card_info(customer_id):
    try:
        sql = "SELECT * FROM cardinfo WHERE customerID = %s"
        cursor_ans = con_sql(sql, (customer_id,))
        card_info_list = cursor_ans.fetchall()
        # print("查询结果:", card_info_list)
        
        result = []
        for row in card_info_list:
            # row 是字典类型，直接用字段名访问
            open_date = row["openDate"].strftime('%Y-%m-%d %H:%M:%S') \
                if isinstance(row["openDate"], datetime.datetime) else row["openDate"]
            
            card_dict = {
                "cardID": row["cardID"],
                "curID": row["curID"],
                "savingID": row["savingID"],
                "openDate": open_date,
                "openMoney": float(row["openMoney"]) if isinstance(row["openMoney"], Decimal) else row["openMoney"],
                "balance": float(row["balance"]) if isinstance(row["balance"], Decimal) else row["balance"],
                "pass": row["pass"],
                "IsReportLoss": row["IsReportLoss"],
                "customerID": row["customerID"]
            }
            result.append(card_dict)
        return result
    
    except Exception as e:
        print(f"查询卡信息失败: {customer_id}，具体异常: {str(e)}")
        return []

def get_user_trade_flow(customer_id):
    try:
        # 查询用户的所有卡号
        card_info_list = get_user_card_info(customer_id)
        card_ids = [card["cardID"] for card in card_info_list]

        result = {}
        for card_id in card_ids:
            # 查询每张卡的交易流水
            sql = "SELECT * FROM tradeinfo WHERE cardID = %s"
            cursor_ans = con_sql(sql, (card_id,))
            trade_flow_list = cursor_ans.fetchall()

            flow_result = []
            for row in trade_flow_list:
                trade_date = row["tradeDate"].strftime('%Y-%m-%d %H:%M:%S') if isinstance(row["tradeDate"], datetime.datetime) else row["tradeDate"]
                flow_dict = {
                    "tradeDate": trade_date,
                    "tradeType": row["tradeType"],
                    "tradeMoney": float(row["tradeMoney"]) if isinstance(row["tradeMoney"], Decimal) else row["tradeMoney"],
                    "remark": row["remark"]
                }
                flow_result.append(flow_dict)

            result[card_id] = flow_result

        return result
    except Exception as e:
        print(f"查询账户流水失败: {customer_id}，具体异常: {str(e)}")
        return {}

def is_sql_error(result):
    #检查是否是 SQL 错误返回
    return (
        isinstance(result, tuple) and
        len(result) == 2 and
        isinstance(result[0], type) and
        issubclass(result[0], Exception)
    )

# @app.route("/")
# def index():
#     return render_template('1.html')

# @app.route("/login", methods=["post"])
# def login():
#     name = request.form.get("username")
#     pwd = request.form.get("password")
#     # print(f"收到数据：name={name}, pwd={pwd}")
#     return f"{name},{pwd}"

@app.route("/")
def bank_homepage():
    return render_template('bank_home.html')

@app.route("/register")
def register_homepage():
    return render_template('register_home.html')

@app.route("/personal")
def personal_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    # print(session)
    # 重新查询余额（关键新增代码）
    customerid = user_data['customerid']
    code_sum = "SELECT SUM(balance) AS total_balance FROM cardinfo WHERE customerID = %s"
    cursor_sum = con_sql(code_sum, (customerid))
    cursor_select_sum = cursor_sum.fetchone()
    new_balance = cursor_select_sum.get('total_balance') or 0
    
    # 更新 Session 中的余额
    user_data['balance'] = str(new_balance)
    session['user_data'] = user_data
    return render_template('personal_home.html', user=user_data)

@app.route("/account")
def account_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('account_home.html', user=user_data)

@app.route("/trade")
def trade_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('trade_home.html', user=user_data)

@app.route('/savemoney')
def savemoney_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('savemoney_home.html', user=user_data)

@app.route("/flow")
def flow_homepage():
    user_data = session.get('user_data')  # 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  # 确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)  # 查询卡信息
    trade_flow_info = get_user_trade_flow(customer_id)  # 查询账户流水信息
    session['user_data']['card_info'] = card_info_list  # 将卡信息存入 session
    session['user_data']['trade_flow_info'] = trade_flow_info  # 将账户流水信息存入 session
    user_data = session.get('user_data')  # 从 Session 中获取用户信息
    if not user_data:  # 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('flow_home.html', user=user_data)

@app.route('/createcard')
def createcard_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('createCard_home.html')

@app.route('/changeinfo')
def changeinfo_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('changeinfo_home.html')

@app.route('/loss')
def loss_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('loss_home.html', user=user_data)

@app.route("/login", methods=["post"])
def login():
    error_msg=None

    id = request.form.get("login-username")
    pwd = request.form.get("login-password")
    # print(f"收到数据：id={id}, pwd={pwd}")

    if id == 'admin' and pwd == 'admin123':
        try:
            # 启动 app.py 作为后台进程
            import subprocess
            import os
            
            # 使用绝对路径或相对路径
            app_path = r"D:\Desktop\学习\PythonCreate\数据库\银行\app.py"
            
            # 启动 app.py 并捕获进程对象
            process = subprocess.Popen(['python', app_path])
            
            # 等待一小段时间让 app.py 有机会启动
            import time
            time.sleep(2)
            
            # 引导用户浏览器访问管理系统
            return """
            <html>
            <body>
                <script>
                    alert('管理员登录成功，正在打开管理系统...');
                    window.history.back();
                </script>
            </body>
            </html>
            """
        except Exception as e:
            print(f"启动 app.py 失败: {str(e)}")
            return """
            <html>
            <body>
                <script>
                    alert('启动管理系统失败，请稍后重试！');
                    window.history.back();
                </script>
            </body>
            </html>
            """


    code = "SELECT * FROM userinfo WHERE PID = %s OR telephone = %s"# % (id,id)
    cursor_ans = con_sql(code,(id,id))
    cursor_select = cursor_ans.fetchall()
    if len(cursor_select)>0:
        if pwd == cursor_select[0]['password']:#登录成功
            customerid = cursor_select[0]['customerID']#获取登录用户的customerID
            code_sum = "SELECT SUM(balance) AS total_balance FROM cardinfo WHERE customerID = %s"# % (customerid)
            cursor_sum = con_sql(code_sum,(customerid))
            cursor_select_sum = cursor_sum.fetchone()
            total_balance = cursor_select_sum.get('total_balance')
            session['user_data']={
                "name": cursor_select[0]['customerName'],
                "balance": total_balance if total_balance is not None else 0,  # 处理无记录的情况
                "pid": cursor_select[0]['PID'],
                "customerid": customerid
            }
            return redirect("/personal")
        else:#登录失败
            return """
            <html>
            <body>
                <script>
                    alert('用户名或密码错误，请重新输入！');
                    window.history.back();  // 回到上一页（登录页面）
                </script>
            </body>
            </html>
            """
    else:
        return """
        <html>
        <body>
            <script>
                alert('用户名或密码错误，请重新输入！');
                window.history.back();  // 回到上一页（登录页面）
            </script>
        </body>
        </html>
        """

@app.route("/register", methods=["post"])
def register():
    username = request.form.get("register-username")
    phone = request.form.get("register-phone")
    idcard = request.form.get("register-idcard")
    address = request.form.get("register-address")
    password = request.form.get("register-password")
    confirm_password = request.form.get("register-confirm-password")
    if len(password) < 6:
        return """
            <html>
            <body>
                <script>
                    alert('密码不符合规范，请重新注册！');
                    window.history.back();  // 回到上一页（注册页面）
                </script>
            </body>
            </html>
            """
    if password != confirm_password:
        return """
            <html>
            <body>
                <script>
                    alert('两次输入的密码不一致，请重新注册！');
                    window.history.back();  // 回到上一页（注册页面）
                </script>
            </body>
            </html>
            """
    # print(f"收到数据：username={username},phone={phone},idcard={idcard},address={address},password={password},confirm_password={confirm_password}")
    code0 = "SELECT * FROM userinfo WHERE PID = %s OR telephone = %s"# % (idcard,phone)
    cursor_ans0 = con_sql(code0,(idcard,phone))
    cursor_select0 = cursor_ans0.fetchall()
    if len(cursor_select0) > 0:#已经存在该用户
        return """
            <html>
            <body>
                <script>
                    alert('此身份证或手机号已拥有账户！');
                    window.history.back();  // 回到上一页（注册页面）
                </script>
            </body>
            </html>
            """
    else:#注册成功
        code = "INSERT INTO userInfo (customerName, PID, telephone, address, password) VALUES (%s, %s, %s, %s, %s)"# % (username, idcard, phone, address, password)
        cursor_ans = con_sql(code,(username, idcard, phone, address, password))

        if isinstance(cursor_ans, tuple) and len(cursor_ans) == 2:
                error_type, error_msg = cursor_ans
                # 将异常值存入字符串
                error_str = f"数据库错误类型: {error_type}, 错误信息: {error_msg}"
                print(error_str)  # 这里可以根据需求，比如返回给前端、记录日志等
                return """
                <html>
                <body>
                    <script>
                        alert('注册失败,注册使用的信息不符合规范！');
                        window.location.href = '/personal';
                    </script>
                </body>
                </html>
                """
        return """
        <html>
        <body>
            <script>
                alert('注册成功！');
                window.location.href = '/';// 跳转到登录界面
            </script>
        </body>
        </html>
        """

@app.route('/trade', methods=['POST'])
def trade():
    # 获取表单数据
    payee_name = request.form.get('payee_name')
    payee_cardid = request.form.get('payee_cardid')
    payee_phone = request.form.get('payee_phone')
    payer_card = request.form.get('selected_card')# 获取隐藏字段中的卡号
    payer_money = request.form.get('payer_money')
    payer_password = request.form.get('payer_password')
    # print(payer_card)
    # return payer_card
    # print(f"payee_phone:{payee_phone}")

    if  not payee_phone:
        if payer_card == payee_cardid:
            return"""
            <html>
            <body>
                <script>
                    alert('转账失败,无法向自己转账');
                    window.location.href = '/personal';
                </script>
            </body>
            </html>
            """
        code_name = "SELECT cardinfo.* FROM cardinfo JOIN userinfo ON cardinfo.customerID = userinfo.customerID WHERE userinfo.customerName = %s AND cardinfo.savingID = 1"
        cursor_ans_name = con_sql(code_name,(payee_name))
        cursor_name_select = cursor_ans_name.fetchall()
        if len(cursor_name_select) == 0:
            return """
            <html>
            <body>
                <script>
                    alert('转账失败,收款人用户名有误');
                    window.location.href = '/personal';
                </script>
            </body>
            </html>
            """
    else:
        code_name = "SELECT cardinfo.* FROM cardinfo JOIN userinfo ON cardinfo.customerID = userinfo.customerID WHERE userinfo.customerName = %s AND cardinfo.savingID = 1"
        cursor_ans_name = con_sql(code_name,(payee_name))
        cursor_name_select = cursor_ans_name.fetchall()
        if len(cursor_name_select) == 0:
            return """
            <html>
            <body>
                <script>
                    alert('转账失败,收款人用户名有误');
                    window.location.href = '/personal';
                </script>
            </body>
            </html>
            """
        code = "SELECT cardinfo.* FROM cardinfo JOIN userinfo ON cardinfo.customerID = userinfo.customerID WHERE userinfo.telephone = %s AND cardinfo.savingID = 1"
        cursor_ans = con_sql(code,(payee_phone))
        cursor_select = cursor_ans.fetchall()
        payee_cardid = cursor_select[0]['cardID']
        if payer_card == payee_cardid:
            return"""
            <html>
            <body>
                <script>
                    alert('转账失败,无法向自己转账');
                    window.location.href = '/personal';
                </script>
            </body>
            </html>
            """


    code = "SELECT * FROM cardinfo WHERE cardID = %s"
    cursor_ans = con_sql(code,(payer_card))
    cursor_select = cursor_ans.fetchall()
    if len(cursor_select) > 0:
        if payer_password == cursor_select[0]['pass']:#密码正确
            # code_trade_payer = "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)"
            # code_trade_payee = "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)"
            # con_sql(code_trade_payer,('NOW()','转账',payer_card,payer_money,'转至{payee_cardid},金额:{payer_money}'))
            # con_sql(code_trade_payer,('NOW()','收账',payer_card,payer_money,'接收来自{payer_card}的转账'))
            trade_remark_payer = f"转至{payee_cardid},金额:{payer_money}"
            trade_remark_payee = f"接收来自{payer_card}的转账"
            result1 = con_sql(
                "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)",
                (datetime.datetime.now(), '转账', payer_card, payer_money, trade_remark_payer)
            )
            result2 = con_sql(
                "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)",
                (datetime.datetime.now(), '收账', payee_cardid, payer_money, trade_remark_payee)
            )

            if is_sql_error(result1):
                error_type, error_msg = result1
                error_str = f"错误信息: {error_msg}"
                print(error_str)
                return render_template(
                    'error_alert.html',
                    error_msg=error_str,
                    redirect_url='/personal'
                )

            if is_sql_error(result2):
                error_type, error_msg = result2
                error_str = f" 错误信息: {error_msg}"
                print(error_str)
                return render_template(
                    'error_alert.html',
                    error_msg=error_str,
                    redirect_url='/personal'
                )

            return"""
            <html>
            <body>
                <script>
                    alert('转账成功！');
                    window.location.href = 'personal'
                </script>
            </body>
            </html>
            """
        else:
            return"""
            <html>
            <body>
                <script>
                    alert('密码错误！');
                    window.location.href = 'personal'
                </script>
            </body>
            </html>
            """
    else:
        return"""
        <html>
        <body>
            <script>
                alert('错误！没有银行卡！请重新登录！');
                window.location.href = '/'// 回到登录页面
            </script>
        </body>
        </html>
        """
    
@app.route('/savemoney', methods=['POST'])
def savemoney():
    usercard = request.form.get('selected_card')  # 获取隐藏字段中的卡号
    money = request.form.get('money')
    password = request.form.get('password')
    operation = request.form.get('operation_type')

    # 查询卡信息以获取密码
    code = "SELECT * FROM cardinfo WHERE cardID = %s"
    cursor_ans = con_sql(code, (usercard,))
    cursor_select = cursor_ans.fetchall()

    if len(cursor_select) > 0:
        if password == cursor_select[0]['pass']:  # 密码正确
            if operation == 'recharge':
                # 充值操作
                result = con_sql(
                    "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney) VALUES (%s, %s, %s, %s)",
                    (datetime.datetime.now(), '存款', usercard, money)
                )
                if is_sql_error(result):
                    error_type, error_msg = result
                    error_str = f"错误信息: {error_msg}"
                    print(error_str)
                    return render_template(
                        'error_alert.html',
                        error_msg=error_str,
                        redirect_url='/personal'
                    )
                return """
                <html>
                <body>
                    <script>
                        alert('充值成功！');
                        window.location.href = '/personal'
                    </script>
                </body>
                </html>
                """
            elif operation == 'withdraw':
                # 提现操作
                result = con_sql(
                    "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney) VALUES (%s, %s, %s, %s)",
                    (datetime.datetime.now(), '取款', usercard, money)
                )
                if is_sql_error(result):
                    error_type, error_msg = result
                    error_str = f"错误信息: {error_msg}"
                    print(error_str)
                    return render_template(
                        'error_alert.html',
                        error_msg=error_str,
                        redirect_url='/personal'
                    )
                return """
                <html>
                <body>
                    <script>
                        alert('提现成功！');
                        window.location.href = '/personal'
                    </script>
                </body>
                </html>
                """
            else:
                return """
                <html>
                <body>
                    <script>
                        alert('操作类型错误！');
                        window.location.href = '/personal'
                    </script>
                </body>
                </html>
                """
        else:
            return """
            <html>
            <body>
                <script>
                    alert('密码错误！');
                    window.location.href = '/personal'
                </script>
            </body>
            </html>
            """
    else:
        return """
        <html>
        <body>
            <script>
                alert('错误！没有银行卡！请重新登录！');
                window.location.href = '/'  # 回到登录页面
            </script>
        </body>
        </html>
        """

@app.route('/createcard', methods=['POST'])
def createcard():
    # 获取表单数据
    pid = request.form.get("pid")
    phone = request.form.get("phone")
    password = request.form.get("password")
    openmoney = request.form.get("openmoney")  # 开户金额
    cardtype = request.form.get("cardtype")    # 卡类型（1/2）
    pwd = request.form.get("pwd")              # 新卡密码

    if not pwd.isdigit() or len(pwd) != 6:
        return"""
        <script>
            alert('新卡密码必须是六位数字！');
            window.history.back();
        </script>
        """

    # 从 session 获取用户信息
    user_data = session.get('user_data')
    if not user_data or 'pid' not in user_data:
        return """
        <script>
            alert('请先登录！');
            window.location.href = '/';
        </script>
        """

    # 从 session['user_data'] 中获取 pid
    session_pid = user_data['pid']

    # 根据 pid 查询 user_id
    query_code = "SELECT customerid FROM userinfo WHERE PID = %s"
    cursor = con_sql(query_code, (session_pid,))
    result = cursor.fetchone()
    if not result:
        return """
        <script>
            alert('用户信息异常，请重新登录！');
            window.location.href = '/';
        </script>
        """
    user_id = result['customerid']  # 根据表结构调整字段名

    user_data_query = "SELECT PID, telephone, password FROM userinfo WHERE customerid = %s"
    user_data_cursor = con_sql(user_data_query, (user_id,))
    user_data = user_data_cursor.fetchone()

    # 定义错误消息
    error_msg = ""
    if pid != user_data['PID']:
        error_msg = "身份证号码不正确！"

    elif phone != user_data['telephone']:
        error_msg = "手机号不正确！"

    elif password != user_data['password']:
        error_msg = "账户密码不正确！"

    if error_msg:
        return f"""
        <script>
            alert('{error_msg}');
            window.history.back();
        </script>
        """

    while True:
        random_part = ''.join(random.choices(string.digits, k=8))
        card_id = f"10103576{random_part}"

        # 校验卡号是否已存在
        check_code = "SELECT cardID FROM cardinfo WHERE cardID = %s"
        check_cursor = con_sql(check_code, (card_id,))
        existing_card = check_cursor.fetchone()
        if not existing_card:
            break  # 卡号唯一，跳出循环

    # 构造插入语句，根据 cardinfo 表字段调整
    insert_code = """
    INSERT INTO cardinfo (cardID, curID, savingID, openDate, openMoney, balance, pass, IsReportLoss, customerID) 
    VALUES (%s, %s, %s, NOW(), %s, %s, %s, %s, %s)
    """
    # 假设货币类型 curID 默认为 1（需根据实际业务调整），IsReportLoss 默认为 0（未挂失）
    cur_id = 'RMB'
    is_report_loss = 0
    # 开户金额和余额初始都为 openmoney
    balance = openmoney
    # 执行插入操作
    insert_cursor = con_sql(insert_code, (
        card_id,
        cur_id,
        cardtype,
        openmoney,
        balance,
        pwd,
        is_report_loss,
        user_id
    ))

    # 简单判断插入是否成功（可根据实际情况优化，比如判断受影响行数等）
    if insert_cursor:
        return """
        <script>
            alert('开卡成功！');
            window.location.href = '/personal';
        </script>
        """
    else:
        return """
        <script>
            alert('开卡失败，请稍后重试！');
            window.history.back();
        </script>
        """
    
@app.route('/changeinfo', methods=['GET', 'POST'])
def changeinfo():
    user_data = session.get('user_data')
    if not user_data or 'customerid' not in user_data:
        return redirect('/')

    user_id = user_data['customerid']
    error_msg = ""
    active_form = None  # 当前激活的表单类型
    form_submitted = False  # 表单是否已提交

    # 获取用户真实信息
    user_info = con_sql(
        "SELECT PID, telephone, password FROM userinfo WHERE customerid = %s", 
        (user_id,)
    ).fetchone()

    if not user_info:
        return redirect('/')

    # 获取用户可用银行卡
    card_list = con_sql(
        "SELECT cardID FROM cardinfo WHERE customerID = %s AND IsReportLoss = '0'", 
        (user_id,)
    ).fetchall()

    if request.method == 'POST':
        # 确定激活的表单类型
        if 'btn_password' in request.form:
            active_form = 'password'
        elif 'btn_phone' in request.form:
            active_form = 'phone'
        elif 'btn_card' in request.form:
            active_form = 'card'
        elif 'submit_password' in request.form:
            active_form = 'password'
            form_submitted = True
        elif 'submit_phone' in request.form:
            active_form = 'phone'
            form_submitted = True
        elif 'submit_card' in request.form:
            active_form = 'card'
            form_submitted = True

        # 仅在表单提交后进行验证
        if form_submitted:
            # 验证身份信息
            pid = request.form.get('pid')
            telephone = request.form.get('telephone')
            user_password = request.form.get('user_password')

            if not pid or not telephone or not user_password:
                error_msg = "请完成身份验证信息"
            elif pid != user_info['PID']:
                error_msg = "身份证号码不正确"
            elif telephone != user_info['telephone']:
                error_msg = "电话号码不正确"
            elif user_password != user_info['password']:
                error_msg = "账户密码不正确"

            # 如果身份验证通过，继续验证对应表单
            if not error_msg:
                if active_form == 'password':
                    new_pwd1 = request.form.get('new_password1')
                    new_pwd2 = request.form.get('new_password2')
                    if not new_pwd1 or not new_pwd2:
                        error_msg = "请输入新密码"
                    elif new_pwd1 != new_pwd2:
                        error_msg = "两次输入的新密码不一致"
                    else:
                        # 更新密码
                        con_sql(
                            "UPDATE userinfo SET password = %s WHERE customerid = %s", 
                            (new_pwd1, user_id)
                        )
                        return """
                        <script>
                            alert('修改成功！');
                            window.location.href = '/personal';
                        </script>
                        """

                elif active_form == 'phone':
                    new_phone1 = request.form.get('new_phone1')
                    new_phone2 = request.form.get('new_phone2')
                    if not new_phone1 or not new_phone2:
                        error_msg = "请输入新电话号码"
                    elif new_phone1 != new_phone2:
                        error_msg = "两次输入的新电话号码不一致"
                    else:
                        # 更新电话
                        con_sql(
                            "UPDATE userinfo SET telephone = %s WHERE customerid = %s", 
                            (new_phone1, user_id)
                        )
                        return """
                        <script>
                            alert('修改成功！');
                            window.location.href = '/personal';
                        </script>
                        """

                elif active_form == 'card':
                    card_id = request.form.get('card_id')
                    old_card_pwd = request.form.get('old_card_pwd')
                    new_card_pwd = request.form.get('new_card_pwd')
                    
                    if not card_id or not old_card_pwd or not new_card_pwd:
                        error_msg = "请完成银行卡信息"
                    else:
                        # 验证银行卡信息
                        card = con_sql(
                            "SELECT pass FROM cardinfo WHERE cardID = %s AND customerID = %s",
                            (card_id, user_id)
                        ).fetchone()
                        
                        if not card:
                            error_msg = "所选银行卡不存在或不属于当前用户"
                        elif card['pass'] != old_card_pwd:
                            error_msg = "原银行卡密码不正确"
                        else:
                            # 更新银行卡密码
                            con_sql(
                                "UPDATE cardinfo SET pass = %s WHERE cardID = %s",
                                (new_card_pwd, card_id)
                            )
                            return """
                            <script>
                                alert('修改成功！');
                                window.location.href = '/personal';
                            </script>
                            """

    return render_template(
        'changeinfo_home.html',
        error_msg=error_msg,
        active_form=active_form,
        card_list=card_list
    )


if __name__ == '__main__':
    app.run(debug=False)